package org.jeecg.modules.wo.people.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wo.people.entity.WoPeople;
import org.jeecg.modules.wo.people.entity.WoPeople4Show;
import org.jeecg.modules.wo.people.entity.WoPeopleIm;
import org.jeecg.modules.wo.people.service.IWoPeopleService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.wo.persontype.entity.WoPersonType;
import org.jeecg.modules.wo.persontype.service.IWoPersonTypeService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 人员管理
 * @Author: jeecg-boot
 * @Date:   2022-03-22
 * @Version: V1.0
 */
@Api(tags="人员管理")
@RestController
@RequestMapping("/people/woPeople")
@Slf4j
public class WoPeopleController extends JeecgController<WoPeople, IWoPeopleService> {
	@Autowired
	private IWoPeopleService woPeopleService;
	@Autowired
	private IWoPersonTypeService woPersonTypeService;

	 @AutoLog(value = "根据分组获取人员核酸检测数据")
	 @ApiOperation(value="根据分组获取人员核酸检测数据", notes="根据分组获取人员核酸检测数据")
	 @GetMapping(value = "/getNucleicByType")
	 public Result<?> getNucleicByType(@RequestParam(name="typeId", defaultValue="") String typeId,
									   @RequestParam(name="apiModel", defaultValue="device") String apiModel,
									   HttpServletRequest req){
		 woPeopleService.getNucleicByType(apiModel,typeId,0);
		 return Result.OK("核酸数据获取成功！");
	 }

	/**
	  * 分页列表查询
	  *
	  * @param woPeople
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "人员管理-分页列表查询")
	 @ApiOperation(value="人员管理-分页列表查询", notes="人员管理-分页列表查询")
	 @GetMapping(value = "/queryPageListByType")
	 public Result<IPage<WoPeople4Show>> queryPageListByType(WoPeople woPeople, @RequestParam(name="typeId", defaultValue="") String typeId,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="20") Integer pageSize,
												  HttpServletRequest req) {
		 QueryWrapper<WoPeople> queryWrapper = QueryGenerator.initQueryWrapper(woPeople, req.getParameterMap());
		 if(StringUtils.isNotEmpty(typeId)){
			String ids=woPersonTypeService.queryTreeChildIds(typeId);
			 queryWrapper.in("psn_type_id",ids.split(","));
		 }
		 Page<WoPeople> page = new Page<WoPeople>(pageNo, pageSize);
		 queryWrapper.orderByAsc("nucleic_date");
		 IPage<WoPeople> pageList = woPeopleService.page(page, queryWrapper);
		 IPage<WoPeople4Show> rsPageList=new Page<>();
		 rsPageList.setPages(pageList.getPages());
		 rsPageList.setCurrent(pageList.getCurrent());
		 rsPageList.setSize(pageList.getSize());
		 rsPageList.setTotal(pageList.getTotal());
		 List<WoPeople4Show> rslist=new ArrayList<>();
		 for(WoPeople psn:pageList.getRecords()){
			 WoPeople4Show psns=new WoPeople4Show(psn);
			 rslist.add(psns);
		 }
		 rsPageList.setRecords(rslist);
		 return Result.OK(rsPageList);
	 }
	/**
	 * 分页列表查询
	 *
	 * @param woPeople
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "人员管理-分页列表查询")
	@ApiOperation(value="人员管理-分页列表查询", notes="人员管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<WoPeople>> queryPageList(WoPeople woPeople,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WoPeople> queryWrapper = QueryGenerator.initQueryWrapper(woPeople, req.getParameterMap());
		Page<WoPeople> page = new Page<WoPeople>(pageNo, pageSize);
		IPage<WoPeople> pageList = woPeopleService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param woPeople
	 * @return
	 */
	@AutoLog(value = "人员管理-添加")
	@ApiOperation(value="人员管理-添加", notes="人员管理-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody WoPeople woPeople) {
		woPeopleService.save(woPeople);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param woPeople
	 * @return
	 */
	@AutoLog(value = "人员管理-编辑")
	@ApiOperation(value="人员管理-编辑", notes="人员管理-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody WoPeople woPeople) {
		woPeopleService.updateById(woPeople);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "人员管理-通过id删除")
	@ApiOperation(value="人员管理-通过id删除", notes="人员管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		woPeopleService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "人员管理-批量删除")
	@ApiOperation(value="人员管理-批量删除", notes="人员管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.woPeopleService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "人员管理-通过id查询")
	@ApiOperation(value="人员管理-通过id查询", notes="人员管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<WoPeople> queryById(@RequestParam(name="id",required=true) String id) {
		WoPeople woPeople = woPeopleService.getById(id);
		if(woPeople==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(woPeople);
	}

	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;

    /**
    * 导出excel
    *
    * @param request
    * @param woPeople
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WoPeople woPeople) {
		// return super.exportXls(request, woPeople, WoPeople.class, "人员列表");
		String typeId=request.getParameter("typeId");
		String title="人员列表";
		// Step.1 组装查询条件
		QueryWrapper<WoPeople> queryWrapper = QueryGenerator.initQueryWrapper(woPeople, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(StringUtils.isNotBlank(typeId)){
			String ids=woPersonTypeService.queryTreeChildIds(typeId);
			queryWrapper.in("psn_type_id",ids.split(","));
		}
		// Step.2 获取导出数据
		List<WoPeople> pageList = service.list(queryWrapper);
		List<WoPeople> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, WoPeople.class);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		exportParams.setImageBasePath(upLoadPath);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       // return super.importExcel(request, response, WoPeople.class);
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			//获取当前用户核查范围的 分组编码
			LoginUser loginUser= (LoginUser) SecurityUtils.getSubject().getPrincipal();
			String userNucleic=loginUser.getNucleic();
			userNucleic.trim();
			userNucleic.replaceAll("，",",");//将中文逗号换成英文逗号
			QueryWrapper<WoPersonType> queryWrapper=new QueryWrapper<>();
			queryWrapper.in("type_code",userNucleic.split(","));
			List<WoPersonType> myTypelist = woPersonTypeService.list(queryWrapper);
			String ids="";
			for(WoPersonType tp:myTypelist){
				//获取当前用户核查范围的 分组id
				ids+=woPersonTypeService.queryTreeChildIds(tp.getId());//递归查询所有子节点id
			}
			try {
				List<WoPeopleIm> listIm = ExcelImportUtil.importExcel(file.getInputStream(), WoPeopleIm.class, params);
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				long start = System.currentTimeMillis();
				List<WoPeople> list=new ArrayList<>();
				int lSize= listIm.size();
				for (int i=0;i<lSize;i++) {
					WoPeopleIm psnIm=listIm.get(i);
					if(StringUtils.isNotBlank(psnIm.getPerName())
							&&StringUtils.isNotBlank(psnIm.getPerIdcard())
							&&StringUtils.isNotBlank(psnIm.getPsnTypeId())){
						//判断数据的分组id是否在 用户核查范围内
						if(!ids.contains(psnIm.getPsnTypeId())){
							return Result.error("文件导入失败！第" +(i+4)+"行，"+psnIm.getPerName()+"的分组编码不正确，请核对！");
						}
						WoPeople psn=new WoPeople();
						BeanUtils.copyProperties(psnIm, psn);
						list.add(psn);
					}else{
						return Result.error("文件导入失败！第" +(i+4)+"行数据必填项为空！");
					}
				}
				woPeopleService.saveBatch(list);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

}
